//
//  SelectMemberViewController.m
//  zhixinApp
//
//  Created by zhiguanzhl on 2017/11/21.
//  Copyright © 2017年 zhiguanzhl. All rights reserved.
//

#import "SelectMemberViewController.h"
#import "SelectTableViewCell.h"
#import "UpImageCell.h"
#import "SingleChatViewController.h"
#import "CreateGroupViewController.h"
#import "SelectMemberViewController.h"
#import "GroupInfoViewController.h"


@implementation SelectNumModel
- (NSMutableArray *)selectIdArray{
    if (!_selectIdArray) {
        _selectIdArray = [NSMutableArray array];
    }
    return _selectIdArray;
}

- (NSMutableArray *)models{
    
    if (!_models) {
        _models = [NSMutableArray array];
    }
    return _models;
}

- (NSMutableArray *)selectIndexPathRow{
    
    if (!_selectIndexPathRow) {
        _selectIndexPathRow = [NSMutableArray array];
    }
    return _selectIndexPathRow;
}

@end


@interface SelectMemberViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableView;
//@property (nonatomic,strong)NSMutableArray *addNameArr;
//@property (nonatomic,strong)NSMutableArray *nameArr;
@property (nonatomic,strong)NSMutableArray *idArr;
@property (nonatomic,strong)NSMutableArray *countArr;
@property (nonatomic,strong)NSNumber *numberPara;

//选中的btn对应的id
@property (nonatomic,strong)NSMutableArray *selctIdArr;
@property (nonatomic,strong)UILabel *countLable;
@property (nonatomic,assign)NSInteger count;

@property (nonatomic,assign)int markIndex;

//请求下来的列表对应的model
@property (nonatomic,strong)NSMutableArray *modalArr;

@property (nonatomic, strong) UIButton *btn;

@end

@implementation SelectMemberViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"通讯录";
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT-64-40) style:UITableViewStylePlain];
    self.tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:tableView];
    self.count = 0;
    [self setBottomView];
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //    [self.tableView.mj_header beginRefreshing];
    self.countLable.text = [NSString stringWithFormat:@"%ld",(long)self.numModel.num];
    [self loadDataWithID:self.numberPara];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
#warning 改
    if (self.block) {
        self.block(self.numModel.models);
    }

}

//获取组织架构
- (void)loadDataWithID:(NSNumber *)numberId{
    
    NSMutableDictionary * paramDict = [[NSMutableDictionary alloc] init];
    
//    [paramDict setValue: [DataCenter shareInstence].companyId forKey:@"companyId"];
    [paramDict setValue: self.companyId forKey:@"companyId"];
    [paramDict setValue:numberId forKey:@"deptId"];
    @WeakObj(self);
    [ZLHXHelper postURL:@"organization/dept" paramDict:paramDict completion:^(NSDictionary *responseObject) {
        
        NSDictionary *dic = [responseObject objectForKey:@"obj"];
        
        NSArray *dataArr = [dic objectForKey:@"depts"];
        NSArray *userArr = [dic objectForKey:@"users"];
        
        [selfWeak.modalArr removeAllObjects];
        
        if (dataArr) {
            
            for (NSDictionary *dic in dataArr) {
                
                SelectModel *deptsModel = [SelectModel mj_objectWithKeyValues:dic];
                [self.modalArr addObject:deptsModel];
                
            }
        }
        
        if (userArr) {
            
            for (NSDictionary *dic in userArr) {
                SelectModel *userModel = [SelectModel mj_objectWithKeyValues:dic];
                [self.modalArr addObject:userModel];
            }
        }
        
        [selfWeak.idArr removeAllObjects];
        [selfWeak.countArr removeAllObjects];
        
        for (int i = 0; i<dataArr.count; i++) {
            
            NSInteger iid = [[dataArr[i] valueForKey:@"id"] integerValue];            NSNumber *idNumber = [NSNumber numberWithInteger:iid];

            [selfWeak.idArr addObject:idNumber];
            NSInteger count = [[dataArr[i] valueForKey:@"total"] integerValue];            NSNumber *countNumber = [NSNumber numberWithInteger:count];
            [selfWeak.countArr addObject:countNumber];
            
        }
        
        for (int j=0; j<userArr.count; j++) {

            NSInteger iid = [[userArr[j] valueForKey:@"id"] integerValue];            NSNumber *idNumber = [NSNumber numberWithInteger:iid];
            [selfWeak.idArr addObject:idNumber];
        }
        
        
        //⚠️单元格滑动／刷新／push都会重置单元格，避免累加，所以先删除再累加
        if (!self.isCreat) {//群设置进入
            //对比看是否部分成员已经选中
            for (NSString *loginName in self.occupanys) {
                NSMutableArray *arr = [NSMutableArray array];
                for (SelectModel *model in self.numModel.models) {
                    if ([model.loginName isEqualToString:loginName]) {
                        [arr addObject:model];
                    }
                }
                [self.numModel.models removeObjectsInArray:arr];
                SelectModel *model = [[SelectModel alloc] init];
                model.loginName = loginName;
                [self.numModel.models addObject:model];
            }
        }
        
        self.countLable.text = [NSString stringWithFormat:@"%ld",self.numModel.models.count];
        [selfWeak.tableView reloadData];

//        [selfWeak.tableView.mj_header endRefreshing];
        
    } error:^(NSError *error) {
        
//        [selfWeak.tableView.mj_header endRefreshing];
    }];
}

- (void)sureAction:(UIButton *)sender{
   

    if ([self.countLable.text isEqualToString:@"0"]) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
    if (self.isCreat) {//创建群
        
        if (self.numModel.models.count == 1) {
            //只有一个人，进入单聊界面
            SelectModel *model = self.numModel.models.lastObject;
            SingleChatViewController * singleChatVC =    [[SingleChatViewController alloc] initWithConversationChatter:model.loginName conversationType:EMConversationTypeChat];
            
            [self.navigationController pushViewController:singleChatVC animated:YES];
            
        }else{//群设置
            
//            [self pushQunsuccess:^(NSMutableArray *names, NSMutableArray *loginNames) {
//                CreateGroupViewController *creatGroupVC = [[CreateGroupViewController alloc] init];
            
//                creatGroupVC.names = names;
//                creatGroupVC.loginNames = loginNames;
//                [self.navigationController pushViewController:creatGroupVC animated:YES];
//
//            }];
            
            
            CreateGroupViewController *creatGroupVC = [[CreateGroupViewController alloc] init];
            creatGroupVC.companyId = self.companyId;
            creatGroupVC.block = ^(NSMutableArray *allModels) {
                self.numModel.models = allModels;
                self.numModel.num = allModels.count;
                [self.tableView reloadData];
            };
            
            creatGroupVC.allModels = self.numModel.models;
            [self.navigationController pushViewController:creatGroupVC animated:YES];
        }
        
    }else{//拉人进群,加人
        
//        [self pushQunsuccess:^(NSMutableArray *names, NSMutableArray *loginNames) {

                //直接调环信
        NSData *data = [[NSUserDefaults standardUserDefaults]valueForKey:@"numberArr"];
        NSArray *numberSArr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
         NSMutableArray *memeberArr = [[NSMutableArray alloc] init];
        [memeberArr removeAllObjects];
        //获取另外添加的人
        NSMutableArray *logainNames = [[NSMutableArray alloc] init];
        for (SelectModel *model in self.numModel.models) {
           
            if (![self.occupanys containsObject:model.loginName]) {
                //获取另外添加的人
                [logainNames addObject:model.loginName];
            }
            
        }

        
        
//                    [[EMClient sharedClient].groupManager addOccupants:logainNames toGroup:self.conversationId welcomeMessage:nil error:nil];

        //掉后台接口把添加的人穿过去
        [self addMembersWithGroupId:self.conversationId withMembers:logainNames];
        
        for (UIViewController *temp in self.navigationController.viewControllers) {
            if ([temp isKindOfClass:[GroupInfoViewController class]]) {
                GroupInfoViewController *vc = (GroupInfoViewController *)temp;
                [vc.occupantArr addObjectsFromArray:logainNames];
                
                for (NSString *nameStr in vc.occupantArr) {
                    NSString *titleName = [Tool getHeadNameWithArr:numberSArr withString:nameStr];
                    
                    [memeberArr addObject:titleName];
                }
            vc.memeberArr = memeberArr;
                
            [self.navigationController popToViewController:vc  animated:YES];
            }
        }

    }
    
}


- (void)addMembersWithGroupId:(NSString *)groupId withMembers:(NSArray *)members{
    NSMutableDictionary * paramDict = [[NSMutableDictionary alloc] init];
    
    [paramDict setValue: self.conversationId forKey:@"groupId"];
    [paramDict setValue:members forKey:@"members"];
//    @WeakObj(self);
    [ZLHXHelper postURL:@"im/addGroupUserBatch" paramDict:paramDict completion:^(NSDictionary *responseObject) {
        
            iToast *itost = [[iToast alloc] initWithText:@"添加成功"];
            [itost show];
        
    } error:^(NSError *error) {
        
    }];
}

- (void)setBottomView{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,kSCREEN_HEIGHT-40-64 ,kSCREEN_WIDTH, 40)];
    [self.view addSubview:view];
    UILabel *lable = [UILabel labelWithFrame:CGRectMake(15, (view.height-25)*0.5, 160, 25) Font:FONT(16) TextColor:[UIColor colorWithHexString:@"666666"]];
    lable.text = @"已经选择人数";
    [lable sizeToFit];
    [view addSubview:lable];
    
    UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.frame = CGRectMake(kSCREEN_WIDTH-15-80, (view.height-25)*0.5, 80, 25);
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor colorWithHexString:@"2c9ae8"] forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(sureAction:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:sureBtn];
    
    UILabel *countLable = [UILabel labelWithFrame:CGRectMake((view.width-50)*0.5,(view.height-25)*0.5, 50, 25) Font:FONT(16) TextColor:[UIColor colorWithHexString:@"666666"]];
    countLable.textAlignment = 1;
    self.countLable = countLable;
    [view addSubview:countLable];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.idArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    SelectModel *model = self.modalArr[indexPath.row];

    SelectTableViewCell *membersCell = [SelectTableViewCell cellWithTableView:tableView];

    
    for (SelectModel *subModel  in self.numModel.models) {
        if ([model.loginName isEqualToString:subModel.loginName]) {
            membersCell.selectBtn.selected = YES;
            break;
        }
    }
    //滑动时防止复用
    membersCell.selectBtn.enabled = YES;
    for (NSString *loginName in self.occupanys) {
        if ([model.loginName isEqualToString:loginName]) {
            membersCell.selectBtn.enabled = NO;
        }
    }
    
    membersCell.model = self.modalArr[indexPath.row];
    
    membersCell.block = ^(BOOL mask){
        
        [self getCountWithMask:mask indexPathRow:indexPath.row];
        
    };
    
    NSString *str = model.name;
    if (str.length >2) {
        str = [str substringFromIndex:1];
    }
    
    if (self.countArr.count != 0) {
        //加这种情况的原因是避免又有人又有组
        if (indexPath.row <= self.countArr.count-1) {
            
            membersCell.imageV.hidden = NO;
            membersCell.nextLable.hidden = NO;
            membersCell.headBt.hidden = YES;
            membersCell.selectBtn.hidden  = YES;
        membersCell.widthContraint.constant = 0;
            membersCell.lableView.constant = 0;
            
        }else{
            
            membersCell.imageV.hidden = YES;
            membersCell.nextLable.hidden = YES;
            membersCell.selectBtn.hidden  = NO;
            membersCell.headBt.hidden = NO;
            [membersCell.headBt setTitle:str forState:UIControlStateNormal];
        }
    }
    
    if (!self.countArr.count) {
        //到最后的一个人了
        membersCell.imageV.hidden = YES;
        membersCell.nextLable.hidden = YES;
        membersCell.headBt.hidden = NO;
        membersCell.selectBtn.hidden  = NO;
        [membersCell.headBt setTitle:str forState:UIControlStateNormal];
    }

    
    return membersCell
    ;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    //组有pid，单个人没有pid(组没有头视图，人有头视图)
    for (SelectModel *model in self.modalArr) {
        if (model.pid) {
            return 0.1;
            break;
        }
    }
    return 56;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    for (SelectModel *model in self.modalArr) {
        if (model.pid) {
            return nil;
            break;
        }
    }
    
    
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, 56)];
    headerView.backgroundColor = [UIColor whiteColor];
    self.btn.selected = self.isSelected;
    [headerView addSubview:self.btn];
    
    UILabel *lab = [UILabel labelWithFrame:CGRectMake(CGRectGetMaxX(self.btn.frame)+17, 18, 100, 20) Font:FONT(15) TextColor:[UIColor blueColor]];
    lab.textColor = [UIColor colorWithHexString:@"454545"];
    lab.text = @"全部";
    [headerView addSubview:lab];
    
    UIImageView *line = [[UIImageView alloc]initWithFrame:CGRectMake(10, 55.5, kSCREEN_WIDTH, 0.5)];
    line.backgroundColor = KLineColor;
    [headerView addSubview:line];
    
    
    return headerView;
}

- (BOOL)isSelected{
    
    NSMutableArray *arr1 = [NSMutableArray array];
    NSMutableArray *arr2 = [NSMutableArray array];
    
    for (SelectModel *model in self.modalArr) {
        if (model.loginName) {
            [arr1 addObject:model.loginName];
        }

    }
    for (SelectModel *model in self.numModel.models) {
        if (model.loginName) {
            [arr2 addObject:model.loginName];
        }

    }
    
    NSSet *set1 = [NSSet setWithArray:arr1];
    NSSet *set2 = [NSSet setWithArray:arr2];
    
    
    if ([set1 isSubsetOfSet:set2]&&
        (arr1.count == self.modalArr.count)) {
        return YES;
    }
    return NO;
}

- (void)btnAction:(UIButton *)btn{
    
    btn.selected = !btn.selected;
    
    NSMutableArray *deleArr = [NSMutableArray array];
    
    for (SelectModel *model in self.numModel.models) {
        
        for (SelectModel *subModel in self.modalArr) {
            if ([subModel.loginName isEqualToString:model.loginName]) {
                [deleArr addObject:model];
            }
        }
    }
    [self.numModel.models removeObjectsInArray:deleArr];
    
    
    if (btn.selected) {//添加数据
        [self.numModel.models addObjectsFromArray:self.modalArr
         ];
    }
    
    self.numModel.num = self.numModel.models.count;
    self.countLable.text = [NSString stringWithFormat:@"%ld",self.numModel.num];
    
    [self.tableView reloadData];
}

#pragma mark 点击事件的回调
- (void)getCountWithMask:(BOOL)mask indexPathRow:(NSInteger)indexPathRow{
    
    SelectModel *model = self.modalArr[indexPathRow];
    
    if (mask == YES) {//选中状态
         [self.numModel.models addObject:model];
    }else{
        [self.numModel.models removeObject:model];
    }
    
    self.countLable.text = [NSString stringWithFormat:@"%ld",self.numModel.models.count] ;
    self.btn.selected = [self isSelected];
    [self.tableView reloadData];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SelectTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.selectBtn.selected) {
        return;
    }
    
    if (!self.countArr.count) {
        //到最后的一个人了
//        NSLog(@"跳转个人聊天页面");
        cell.selectBtn.selected = YES;
        [self getCountWithMask:YES indexPathRow:indexPath.row];
        
        return;
    }else{
        if (self.countArr.count-1 < indexPath.row) {
//            iToast *toast = [[iToast alloc] initWithText:@"最后一个人了，不可点击"];
//            [toast show];
            cell.selectBtn.selected = YES;
            [self getCountWithMask:YES indexPathRow:indexPath.row];
            return;
        }else {
            
            if ([self.countArr[indexPath.row] integerValue] == 0) {
                iToast *toast = [[iToast alloc] initWithText:@"下级没有人了，不可点击"];
                [toast show];
                return;
            }
            
        }
    }
    
    
    SelectMemberViewController *selectVC = [[SelectMemberViewController alloc] init];
    selectVC.isCreat = self.isCreat;
    selectVC.companyId = self.companyId;
    selectVC.occupanys = self.occupanys;
    selectVC.numberPara = self.idArr[indexPath.row];
    selectVC.numModel = self.numModel;
    selectVC.conversationId = self.conversationId;
    [self.navigationController pushViewController:selectVC animated:YES];

}
//群添加人
//- (void)addGroupUserBatchWith:(NSMutableArray *)loginNameArr
//{
//    NSMutableDictionary * paramDict = [[NSMutableDictionary alloc] init];
//
//    [paramDict setValue: self.conversationId forKey:@"groupId"];
//    [paramDict setValue:loginNameArr forKey:@"members"];
////    @WeakObj(self);
//    [ZLHXHelper postURL:@"im/addGroupUserBatch" paramDict:paramDict completion:^(NSDictionary *responseObject) {
//
//        [self.navigationController popViewControllerAnimated:YES];
//
//        NSLog(@"%@",responseObject);
//
//    } error:^(NSError *error) {
//
//    }];
//
//}


- (NSMutableArray *)idArr{
    if (!_idArr) {
        _idArr = [[NSMutableArray alloc] init];
    }
    
    return _idArr;
}
- (NSMutableArray *)countArr{
    if (!_countArr) {
        _countArr = [[NSMutableArray alloc] init];
    }
    
    return _countArr;
}


- (NSMutableArray *)selctIdArr{
    if (!_selctIdArr) {
        _selctIdArr = [[NSMutableArray alloc] init];
    }
    
    return _selctIdArr;
}

- (NSMutableArray *)modalArr{
    if (!_modalArr) {
        _modalArr = [[NSMutableArray alloc] init];
    }
    
    return _modalArr;
}

- (SelectNumModel *)numModel{
    if (!_numModel) {
        _numModel = [[SelectNumModel alloc]init];
    }
    return _numModel;
}


- (UIButton *)btn{
    if (!_btn) {
        _btn = [[UIButton alloc]initWithFrame:CGRectMake(15, (56-20)*0.5, 20, 20)];
        [_btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        [_btn setImage:kImageName(@"checkbox_notselected") forState:UIControlStateNormal];
        [_btn setImage:kImageName(@"checkbox_selected") forState:UIControlStateSelected];
    }
    return _btn;
}



@end


